﻿using Auto.AlgsAndPush.DTO;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Auto.AlgsAndPush.Services.ResultFilter
{
    public class FilterProcessService
    {
        private readonly HttpClientService _httpClientService;
        public FilterProcessService(HttpClientService httpClient)
        {
            _httpClientService = httpClient;
        }

        /// <summary>
        /// 将多期数据经过滤波转为一期数据
        /// </summary>
        /// <param name="results">拉取的多期数据</param>
        /// <returns></returns>
        public FilterResult ProcessMultiOriginResults(IEnumerable<OriginResult> results)
        {
            var url = "http://www.ce-safe.com:8084/MetroDataApi/api/stableprocessor/calculator";
            try
            {
                var response = _httpClientService.PostByRest(url, results);
                var content = JsonConvert.DeserializeObject<FilterResult>(response.Content);

                var temp = results.Last();
                content.Data = content.Data.Select(x => new PointValue
                {
                    Name = x.Name,
                    Value = x.Value,
                    StationId = temp.Data.FirstOrDefault(d => d.Name == x.Name).StationId
                });

                /**为了区别于滤波数据的时间和真实采集数据的时间，滤波数据时间延迟2mins；同时为了防止滤波配置endtime一致时滤波时间相同，在加一个值*/
                var delay = 2 + results.Count() * 0.1;
                content.Date = temp.Date.AddMinutes(delay);
                Console.WriteLine(temp.Date.AddMinutes(2.5));

                return content;
            }
            catch
            {
                throw new Exception("拉取多期数据出错！");
            }
        }
    }
}
